﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using CoolCode.Services;

namespace CoolCode.Web.UI
{
    public abstract class AuthPage : BasePage, IAuthPage 
    {
        private IMenuService _MenuService;
        public IMenuService MenuService
        {
            get
            {
                if (_MenuService == null)
                {
                    _MenuService = ServiceFactory.Produce<IMenuService>();
                }
                return _MenuService;
            }
        }

        private Role _role;
        public Role Role
        {
            get
            {
                if (_role == null)
                {
                    string url = Request.Url.AbsolutePath;
                    string[] splits = url.Split('/');
                    if (splits.Length < 2)
                        return new Role { AllowAccess = true };
                    string module = splits[splits.Length - 2];
                    string node = splits[splits.Length - 1];
                    if (module == string.Empty)
                        return new Role { AllowAccess = true };
                    int ind = node.IndexOf('.');//if include ".aspx"
                    if (ind > 0)
                        node = node.Substring(0, ind);
                    //Response.Write(string.Format("<div>{0}</div>", UserName+","+module+","+node) );
                    //return new Role { AllowAccess = true };
                    _role = this.MenuService.GetRoleByPage(UserName, module, node);
                }
                return _role;
            }
        }

        protected virtual bool CheckUserRole()
        {
            if (User == null)
            {
                this.ViewLogin();
                return false;
            }

            if (!User.Identity.IsAuthenticated)
            {
                this.ViewLogin();
                return false;
            }

            if (!this.Role.AllowAccess)
            {
                //Response.Write(string.Format("<br/><br/><hr><br/><h3>{0}</h3><hr>", "你没有权限进入本页面！"));
                //Response.End();
                Response.Redirect("~/Views/Home/Message.aspx?msg=" + Utility.UrlEncode( "你没有权限进入本页面！"));
                return false;
            }
            //Page Command
            Action<string> DisableByControlID = controlID =>
            {
                var command = this.FindControl<WebControl>(controlID);
                if (command != null)
                    command.Enabled = false;
            };
            List<string> commandList = new List<string>();
            if (!this.Role.AllowEdit)
            {
                commandList.Add("lnkEdit");
                commandList.Add("lnkUpload");
                commandList.Add("lnkSave");
                commandList.Add("btnSave");
                commandList.Add("lnkSubmit");
            }
            if (!this.Role.AllowDelete)
            {
                commandList.Add("lnkDelete");
            }
            if (!this.Role.AllowExport)
            {
                commandList.Add("lnkExcel");
                commandList.Add("lnkExport");
            }
            commandList.ForEach(c => DisableByControlID(c));

            //Grid Command
            var grid = this.FindControl<GridView>("gvMaster");
            if (grid != null)
                grid.DisableCommand(this.Role);
            grid = this.FindControl<GridView>("gvEntry");
            if (grid != null)
                grid.DisableCommand(this.Role);

            return true;
        }

        protected virtual void InitialPage()
        {
            if (!IsPostBack)
            {
                if (!this.CheckUserRole())
                    return;
            }

            /*在页面postback时，Title是不会postback的，所以Title需要存储在Heading里，
             * 如果postback时需要访问Title，则使用Heading属性来获取Title*/
            //ContextManager.SetText();
            //ContextManager.Initialize();
            //if (this.EnableViewState)
            //    this.Heading = this.Title; 
        }


        protected override void OnLoad(EventArgs e)
        {
            if (!this.CheckUserRole())
                return;
            base.OnLoad(e);
        }


        //public bool CheckUserRole(UserAction action)
        //{
        //    switch (action)
        //    {
        //        case UserAction.Access:
        //            return Role.AllowAccess;
        //        case UserAction.Add:
        //        case UserAction.Edit:
        //            return Role.AllowEdit;
        //        case UserAction.Delete:
        //            return Role.AllowEdit;
        //        default:
        //            return true;
        //    }
        //}
    }
}
